import json
import os
from common.logger import log

def url2name(url: str, method=None, file_type='.har'):
    _url = url.split("?")[0]
    if _url.startswith('/'):
        _url = _url[1:]
    name = _url.replace('/',"_")
    if method:
        name = name + "_" + method
    return name + file_type

def save2json(data: dict, path='har'):
    if not os.path.exists(path):
        os.mkdir(path)
    file_name = url2name(url=data['log']['entries'][0]['request']['url'], method=data['log']['entries'][0]['request']['method'])
    file_name = os.path.join(path, file_name)
    log.i('save har file: {}'.format(file_name))
    with open(file_name, 'w')as f:
        f.write(json.dumps(data, ensure_ascii=False, indent='  '))